package cn.iocoder.yudao.module.erp.service.planinfo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.Month;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.crm.dal.dataobject.product.CrmProductCategoryDO;
import cn.iocoder.yudao.module.crm.dal.mysql.product.CrmProductCategoryMapper;
import cn.iocoder.yudao.module.erp.controller.admin.planinfo.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.accountplanrecord.AccountPlanRecordDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.contractinfo.ContractInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.customeraccount.CustomerAccountDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.customerinfo.CustomerInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.monthplaninfo.MonthPlanInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.planinfo.PlanInfoDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductCategoryDO;
import cn.iocoder.yudao.module.erp.dal.mysql.accountplanrecord.AccountPlanRecordMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.contractinfo.ContractInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.customerinfo.CustomerInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.monthplaninfo.MonthPlanInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.planinfo.PlanInfoMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.product.ErpProductCategoryMapper;
import cn.iocoder.yudao.module.erp.enums.Constant;
import cn.iocoder.yudao.module.erp.enums.DictTypeConstants;
import cn.iocoder.yudao.module.erp.service.accountplanrecord.AccountPlanRecordService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.validation.ConstraintViolationException;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 每日计划 Service 实现类
 *
 * @author mhc
 */
@Service
@Validated
public class PlanInfoServiceImpl implements PlanInfoService {

    @Resource
    private PlanInfoMapper planInfoMapper;

    @Resource
    private AccountPlanRecordMapper accountPlanRecordMapper;

    @Resource
    private AccountPlanRecordService accountPlanRecordService;

    @Resource
    private CustomerInfoMapper customerInfoMapper;

    @Resource
    private ContractInfoMapper contractInfoMapper;

    @Resource
    private MonthPlanInfoMapper monthPlanInfoMapper;

    @Resource
    private ErpProductCategoryMapper erpProductCategoryMapper;

    @Resource
    private CrmProductCategoryMapper crmProductCategoryMapper;

    @Override
    @Transactional
    public boolean calculatePlanInfoCount() {
        //得到每日计划
        List<PlanInfoDO> all=planInfoMapper.selectList();
        for(PlanInfoDO planInfo:all){
            //计算
            //计算
            BigDecimal salePrice=planInfo.getSalePrice();
            BigDecimal saleCount=planInfo.getSaleRealCount();

            BigDecimal saleOtherPrice=planInfo.getSaleOtherPrice()==null?new BigDecimal("0"):planInfo.getSaleOtherPrice();

            //居间总额=居间费*下载量
            BigDecimal saleJjf=saleCount.multiply(saleOtherPrice).setScale(6, RoundingMode.HALF_UP);
            planInfo.setSaleOtherCount(saleJjf);
            //真实价格=居间费+销售单价
            BigDecimal saleRealPrice=salePrice.add(saleOtherPrice);
            planInfo.setSaleRealPrice(saleRealPrice);
            //销售额=销售价格*下载量
            planInfo.setSaleAllCount(salePrice.multiply(saleCount));

            //管输总额=管输单价*下载量
            BigDecimal gsze=planInfo.getLinePrice().multiply(saleCount);
            planInfo.setLineCost(gsze);


            //采购
            BigDecimal bugPrice=planInfo.getBuyPrice();
            BigDecimal bugCount=planInfo.getBuyRealCount();
            //采购居间费
            BigDecimal bugOtherPrice=planInfo.getBuyOtherPrice()==null?new BigDecimal("0"):planInfo.getBuyOtherPrice();
            //采购居间费
            BigDecimal buyjjf=bugCount.multiply(bugOtherPrice);
            planInfo.setBuyOtherCount(buyjjf);

            BigDecimal buyRealPrice=bugPrice.add(bugOtherPrice);
            planInfo.setBuyRealPrice(buyRealPrice);

            planInfo.setBuyAllCount(bugPrice.multiply(bugCount));
            //毛差

            BigDecimal mc=salePrice.subtract(planInfo.getLinePrice()).subtract(bugPrice).subtract(saleOtherPrice).subtract(bugOtherPrice);

            planInfo.setGainCount(mc);
            //总利润=毛差*下载量
            planInfo.setProfit(mc.multiply(planInfo.getSaleRealCount()));
            planInfoMapper.updateById(planInfo);
        }


        return false;
    }

    @Override
    public PlanImportRespVO importPlanList(List<PlanInfoImportVO> importUsers, boolean isUpdateSupport) {
        // 1.1 参数校验
        if (CollUtil.isEmpty(importUsers)) {
            throw exception(IMPORT_PLAN_EXCEPTION);
        }
      /*  // 1.2 初始化密码不能为空
        String initPassword = configApi.getConfigValueByKey(USER_INIT_PASSWORD_KEY);
        if (StrUtil.isEmpty(initPassword)) {
            throw exception(USER_IMPORT_INIT_PASSWORD);
        }*/

        // 2. 遍历，逐个创建 or 更新
        PlanImportRespVO respVO = PlanImportRespVO.builder().createUsernames(new ArrayList<>())
                .failureUsernames(new LinkedHashMap<>()).build();
        int i=1;
        for(PlanInfoImportVO plan:importUsers){
            i++;
            //得到月度计划
            if(StringUtils.isNotBlank(plan.getCompanyName())){
                MonthPlanInfoDO month=monthPlanInfoMapper.selectOne(new LambdaQueryWrapperX<MonthPlanInfoDO>().eq(MonthPlanInfoDO::getName,plan.getCompanyName()));
                if(month==null){
                    respVO.getFailureUsernames().put("第"+i+"行", "月度计划名称不正确");
                     continue;
                }else{
                    plan.setCompanyId(month.getId());
                }
            }else{
                respVO.getFailureUsernames().put("第"+i+"行", "月度计划名称不能为空");
                 continue;
            }

           /* if(StringUtils.isNotBlank(plan.getUpName())){
                ErpProductCategoryDO up=erpp.selectOne(new LambdaQueryWrapperX<CustomerInfoDO>().eq(CustomerInfoDO::getName,plan.getSaleCustomerName()));
                if(saleCustomer==null){
                    respVO.getFailureUsernames().put("第"+i+"行", "销售客户名称不正确");
                     continue;
                }else{
                    plan.setSaleCustomerId(saleCustomer.getId());
                }
            }else{
                respVO.getFailureUsernames().put("第"+i+"行", "销售客户名称不能为空");
                 continue;
            }*/



            if(StringUtils.isNotBlank(plan.getSaleCustomerName())){
                CustomerInfoDO saleCustomer=customerInfoMapper.selectOne(new LambdaQueryWrapperX<CustomerInfoDO>().eq(CustomerInfoDO::getName,plan.getSaleCustomerName()));
                if(saleCustomer==null){
                    respVO.getFailureUsernames().put("第"+i+"行", "销售客户名称不正确");
                     continue;
                }else{
                    plan.setSaleCustomerId(saleCustomer.getId());
                }
            }else{
                respVO.getFailureUsernames().put("第"+i+"行", "销售客户名称不能为空");
                 continue;
            }



            if(StringUtils.isNotBlank(plan.getBuyCustomerName())){
                CustomerInfoDO buyCustomer=customerInfoMapper.selectOne(new LambdaQueryWrapperX<CustomerInfoDO>().eq(CustomerInfoDO::getName,plan.getBuyCustomerName()));
                if(buyCustomer==null){
                    respVO.getFailureUsernames().put("第"+i+"行", "采购客户名称不正确");
                     continue;
                }else{
                    plan.setBuyCustomerId(buyCustomer.getId());
                }
            }else{
                respVO.getFailureUsernames().put("第"+i+"行", "采购客户名称不能为空");
                 continue;
            }
            //上下载点

            if(StringUtils.isNotBlank(plan.getUpName())){
                CrmProductCategoryDO up=crmProductCategoryMapper.selectOne(new LambdaQueryWrapperX<CrmProductCategoryDO>().eq(CrmProductCategoryDO::getId,plan.getUpId()).last(" limit 1"));
                if(up==null){
                    respVO.getFailureUsernames().put("第"+i+"行", "上载点编码不正确");
                     continue;
                }else{
                    plan.setUpId(up.getId());
                }
            }else{
                respVO.getFailureUsernames().put("第"+i+"行", "上载点编码不能为空");
                 continue;
            }


            if(StringUtils.isNotBlank(plan.getDownloadName())){
                ErpProductCategoryDO down=erpProductCategoryMapper.selectOne(new LambdaQueryWrapperX<ErpProductCategoryDO>().eq(ErpProductCategoryDO::getId,plan.getDownloadId()).last(" limit 1"));
                if(down==null){
                    respVO.getFailureUsernames().put("第"+i+"行", "下载点编码不正确");
                     continue;
                }else{
                    plan.setDownloadId(down.getId());
                }
            }else{
                respVO.getFailureUsernames().put("第"+i+"行", "下载点编码不能为空");
                 continue;
            }



            if(StringUtils.isNotBlank(plan.getSaleContractName())){
                ContractInfoDO saleCustomer=contractInfoMapper.selectOne(new LambdaQueryWrapperX<ContractInfoDO>().eq(ContractInfoDO::getName,plan.getSaleContractName()));
                if(saleCustomer==null){
                    respVO.getFailureUsernames().put("第"+i+"行", "销售合同名称不正确");
                   
                     continue;
                }else{
                    if(saleCustomer.getCustomerId().intValue()==plan.getSaleCustomerId().intValue()){
                        plan.setSaleContractId(saleCustomer.getId());
                    }else{
                        respVO.getFailureUsernames().put("第"+i+"行", "合同名称不正确,请填写销售客户的合同名称");
                         continue;
                    }

                }
            }

            if(StringUtils.isNotBlank(plan.getBuyContractName())){
                ContractInfoDO buyCustomer=contractInfoMapper.selectOne(new LambdaQueryWrapperX<ContractInfoDO>().eq(ContractInfoDO::getName,plan.getBuyContractName()));
                if(buyCustomer==null){
                    respVO.getFailureUsernames().put("第"+i+"行", "采购合同名称不正确");
                     continue;
                }else{
                    if(buyCustomer.getCustomerId().intValue()==plan.getBuyCustomerId().intValue()){
                        plan.setBuyContractId(buyCustomer.getId());
                    }else{
                        respVO.getFailureUsernames().put("第"+i+"行", "合同名称不正确,请填写采购客户的合同名称");
                         continue;
                    }

                }
            }


            try {
                ValidationUtils.validate(BeanUtils.toBean(plan, PlanInfoSaveReqVO.class));
            } catch (ConstraintViolationException ex){
                respVO.getFailureUsernames().put("第"+i+"行", ex.getMessage());
                 continue;
            }
            //保存
            PlanInfoDO planInfo=BeanUtils.toBean(plan, PlanInfoDO.class);
            //计算
            BigDecimal salePrice=planInfo.getSalePrice();
            BigDecimal saleCount=planInfo.getSaleRealCount()==null?new BigDecimal("0"):planInfo.getSaleRealCount();

            BigDecimal saleOtherPrice=planInfo.getSaleOtherPrice()==null?new BigDecimal("0"):planInfo.getSaleOtherPrice();

            //居间总额=居间费*下载量
            BigDecimal saleJjf=saleCount.multiply(saleOtherPrice)/*.multiply(new BigDecimal("10000"))*/;
            planInfo.setSaleOtherCount(saleJjf);
            //真实价格=居间费+销售单价
            BigDecimal saleRealPrice=salePrice.add(saleOtherPrice);
            planInfo.setSaleRealPrice(saleRealPrice);
            //销售额=销售价格*下载量
            planInfo.setSaleAllCount(salePrice.multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/);

            //管输总额=管输单价*下载量
            BigDecimal gsze=planInfo.getLinePrice().multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/;
            planInfo.setLineCost(gsze);


            //采购
            BigDecimal bugPrice=planInfo.getBuyPrice();
            BigDecimal bugCount=planInfo.getBuyRealCount()==null?new BigDecimal("0"):planInfo.getBuyRealCount();
            //采购居间费
            BigDecimal bugOtherPrice=planInfo.getBuyOtherPrice()==null?new BigDecimal("0"):planInfo.getBuyOtherPrice();
            //采购居间费
            BigDecimal buyjjf=bugCount.multiply(bugOtherPrice)/*.multiply(new BigDecimal("10000"))*/;
            planInfo.setBuyOtherCount(buyjjf);
            //购买额
            BigDecimal buyRealPrice=bugPrice.add(bugOtherPrice);
            planInfo.setBuyRealPrice(buyRealPrice);

            planInfo.setBuyAllCount(bugPrice.multiply(bugCount)/*.multiply(new BigDecimal("10000"))*/);
            //毛差

            BigDecimal mc=salePrice.subtract(planInfo.getLinePrice()).subtract(bugPrice).subtract(saleOtherPrice).subtract(bugOtherPrice);

            // BigDecimal mc=salePrice.subtract(bugPrice).subtract(planInfo.getSaleOtherPrice()).subtract(planInfo.getBuyOtherPrice());
            planInfo.setGainCount(mc);
            //总利润=毛差*下载量
            //planInfo.setProfit(planInfo.getSaleAllCount().subtract(planInfo.getBuyAllCount()).subtract(planInfo.getSaleOtherCount()).subtract(planInfo.getBuyOtherCount()));
            planInfo.setProfit(mc.multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/);


            //
            planInfo.setSaleBillStatus(0);
            planInfo.setSaleAccountStatus(0);
            planInfo.setBuyBillStatus(0);
            planInfo.setBuyAccountStatus(0);
            planInfoMapper.insert(planInfo);

            respVO.getCreateUsernames().add("第"+i+"行");
        }
        /*importUsers.forEach(plan -> {
            // 2.1.1 校验字段是否符合要求
            try {
                ValidationUtils.validate(BeanUtils.toBean(plan, PlanInfoSaveReqVO.class));
            } catch (ConstraintViolationException ex){
                respVO.getFailureUsernames().put(, ex.getMessage());
                return;
            }
            // 2.1.2 校验，判断是否有不符合的原因
            try {
                validatePlanInfoExists(null, null, importUser.getMobile(), importUser.getEmail(),
                        importUser.getDeptId(), null);
            } catch (ServiceException ex) {
                respVO.getFailureUsernames().put(importUser.getUsername(), ex.getMessage());
                return;
            }

            // 2.2.1 判断如果不存在，在进行插入
            AdminUserDO existUser = userMapper.selectByUsername(importUser.getUsername());
            if (existUser == null) {
                userMapper.insert(BeanUtils.toBean(importUser, AdminUserDO.class)
                        .setPassword(encodePassword(initPassword)).setPostIds(new HashSet<>())); // 设置默认密码及空岗位编号数组
                respVO.getCreateUsernames().add(importUser.getUsername());
                return;
            }
            // 2.2.2 如果存在，判断是否允许更新
            if (!isUpdateSupport) {
                respVO.getFailureUsernames().put(importUser.getUsername(), USER_USERNAME_EXISTS.getMsg());
                return;
            }
            AdminUserDO updateUser = BeanUtils.toBean(importUser, AdminUserDO.class);
            updateUser.setId(existUser.getId());
            userMapper.updateById(updateUser);
            respVO.getUpdateUsernames().add(importUser.getUsername());
        });*/
        return respVO;
    }

    @Override
    @Transactional
    public Long createPlanInfo(PlanInfoSaveReqVO createReqVO) {
        // 插入
        PlanInfoDO planInfo = BeanUtils.toBean(createReqVO, PlanInfoDO.class);
        //planInfo.setGainCount(new BigDecimal(1));
        planInfo.setSaleAccountStatus(0);

     /*   planInfo.setCompanyId(SecurityFrameworkUtils.getLoginUserDeptId());*/

        //计算
        BigDecimal salePrice=createReqVO.getSalePrice();
        BigDecimal saleCount=createReqVO.getSaleRealCount()==null?new BigDecimal("0"):createReqVO.getSaleRealCount();

        BigDecimal saleOtherPrice=createReqVO.getSaleOtherPrice()==null?new BigDecimal("0"):createReqVO.getSaleOtherPrice();

        //居间总额=居间费*下载量
        BigDecimal saleJjf=saleCount.multiply(saleOtherPrice)/*.multiply(new BigDecimal("10000"))*/;
        planInfo.setSaleOtherCount(saleJjf);
        //真实价格=居间费+销售单价
        BigDecimal saleRealPrice=salePrice.add(saleOtherPrice);
        planInfo.setSaleRealPrice(saleRealPrice);
        //销售额=销售价格*下载量
        planInfo.setSaleAllCount(salePrice.multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/);

        //管输总额=管输单价*下载量
        BigDecimal gsze=planInfo.getLinePrice().multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/;
        planInfo.setLineCost(gsze);


        //采购
        BigDecimal bugPrice=createReqVO.getBuyPrice();
        BigDecimal bugCount=createReqVO.getBuyRealCount()==null?new BigDecimal("0"):createReqVO.getBuyRealCount();
        //采购居间费
        BigDecimal bugOtherPrice=createReqVO.getBuyOtherPrice()==null?new BigDecimal("0"):createReqVO.getBuyOtherPrice();
        //采购居间费
        BigDecimal buyjjf=bugCount.multiply(bugOtherPrice)/*.multiply(new BigDecimal("10000"))*/;
        planInfo.setBuyOtherCount(buyjjf);
        //购买额
        BigDecimal buyRealPrice=bugPrice.add(bugOtherPrice);
        planInfo.setBuyRealPrice(buyRealPrice);

        planInfo.setBuyAllCount(bugPrice.multiply(bugCount)/*.multiply(new BigDecimal("10000"))*/);
        //毛差

        BigDecimal mc=salePrice.subtract(planInfo.getLinePrice()).subtract(bugPrice).subtract(saleOtherPrice).subtract(bugOtherPrice);

        // BigDecimal mc=salePrice.subtract(bugPrice).subtract(planInfo.getSaleOtherPrice()).subtract(planInfo.getBuyOtherPrice());
        planInfo.setGainCount(mc);
        //总利润=毛差*下载量
        //planInfo.setProfit(planInfo.getSaleAllCount().subtract(planInfo.getBuyAllCount()).subtract(planInfo.getSaleOtherCount()).subtract(planInfo.getBuyOtherCount()));
        planInfo.setProfit(mc.multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/);


        //
        planInfo.setSaleBillStatus(0);
        planInfo.setSaleAccountStatus(0);
        planInfo.setBuyBillStatus(0);
        planInfo.setBuyAccountStatus(0);
        planInfoMapper.insert(planInfo);

        //添加销售公司记录 1销售2采购3付款4收款
      /*  AccountPlanRecordDO ap=new AccountPlanRecordDO();
        ap.setCustomerId(planInfo.getSaleCustomerId());
        ap.setMoneyCount(planInfo.getSaleAllCount().negate());
        ap.setType(Constant.AccountPlanRecord_TYPE.销售.getValue());
        ap.setTypeId(planInfo.getId());
        ap.setPayDate(planInfo.getNowTime());
        accountPlanRecordService.createAccountPlanRecord(ap);

        //添加采购公司记录
        AccountPlanRecordDO cg=new AccountPlanRecordDO();
        cg.setCustomerId(planInfo.getBuyCustomerId());
        cg.setMoneyCount(planInfo.getBuyAllCount());
        cg.setType(Constant.AccountPlanRecord_TYPE.采购.getValue());
        cg.setTypeId(planInfo.getId());
        cg.setPayDate(planInfo.getNowTime());
        accountPlanRecordService.createAccountPlanRecord(cg);*/





        // 返回
        return planInfo.getId();
    }

    @Autowired
    private ConcurrentHashMap<String, CustomerAccountDO> concurrentHashMap;

    @Autowired
    private ConcurrentHashMap<String, MonthPlanInfoDO> monthMap;

    @Autowired
    private ConcurrentHashMap<String, ContractInfoDO> contractMap;

    @Override
    @Transactional
    public Long finishPlanInfo(PlanInfoFinishReqVO createReqVO) {
        // 插入
        PlanInfoDO planInfo = BeanUtils.toBean(createReqVO, PlanInfoDO.class);
        //已结算
        PlanInfoDO old=planInfoMapper.selectById(createReqVO.getId());
        boolean xg=false;
        if(old.getStatus()==0){
            planInfo.setStatus(1);
        }else{
            //修改
            xg=true;
        }


        //计算
        BigDecimal salePrice=createReqVO.getSalePrice();
        BigDecimal saleCount=createReqVO.getSaleRealCount();

        BigDecimal saleOtherPrice=createReqVO.getSaleOtherPrice()==null?new BigDecimal("0"):createReqVO.getSaleOtherPrice();

        //居间总额=居间费*下载量
        BigDecimal saleJjf=saleCount.multiply(saleOtherPrice)/*.multiply(new BigDecimal("10000"))*/.setScale(6, RoundingMode.HALF_UP);
        planInfo.setSaleOtherCount(saleJjf);
        //真实价格=居间费+销售单价
        BigDecimal saleRealPrice=salePrice.add(saleOtherPrice);
        planInfo.setSaleRealPrice(saleRealPrice);
        //销售额=销售价格*下载量
        planInfo.setSaleAllCount(salePrice.multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/);

        //管输总额=管输单价*下载量
        BigDecimal gsze=planInfo.getLinePrice().multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/;
        planInfo.setLineCost(gsze);


        //采购
        BigDecimal bugPrice=createReqVO.getBuyPrice();
        BigDecimal bugCount=createReqVO.getBuyRealCount();
        //采购居间费
        BigDecimal bugOtherPrice=createReqVO.getBuyOtherPrice()==null?new BigDecimal("0"):createReqVO.getBuyOtherPrice();
        //采购居间费
        BigDecimal buyjjf=bugCount.multiply(bugOtherPrice)/*.multiply(new BigDecimal("10000"))*/;
        planInfo.setBuyOtherCount(buyjjf);
        //购买额
        BigDecimal buyRealPrice=bugPrice.add(bugOtherPrice);
        planInfo.setBuyRealPrice(buyRealPrice);

        planInfo.setBuyAllCount(bugPrice.multiply(bugCount)/*.multiply(new BigDecimal("10000"))*/);
        //毛差

        BigDecimal mc=salePrice.subtract(planInfo.getLinePrice()).subtract(bugPrice).subtract(saleOtherPrice).subtract(bugOtherPrice);

        // BigDecimal mc=salePrice.subtract(bugPrice).subtract(planInfo.getSaleOtherPrice()).subtract(planInfo.getBuyOtherPrice());
        planInfo.setGainCount(mc);
        //总利润=毛差*下载量
        //planInfo.setProfit(planInfo.getSaleAllCount().subtract(planInfo.getBuyAllCount()).subtract(planInfo.getSaleOtherCount()).subtract(planInfo.getBuyOtherCount()));
        planInfo.setProfit(mc.multiply(planInfo.getSaleRealCount())/*.multiply(new BigDecimal("10000"))*/);

        //
      /*  planInfo.setSaleBillStatus(0);
        planInfo.setSaleAccountStatus(0);
        planInfo.setBuyBillStatus(0);
        planInfo.setBuyAccountStatus(0);*/



        if(xg){
            AccountPlanRecordDO ap=accountPlanRecordMapper.selectOne(new LambdaQueryWrapper<AccountPlanRecordDO>().eq(AccountPlanRecordDO::getCustomerId,planInfo.getSaleCustomerId())
                    .eq(AccountPlanRecordDO::getTypeId,planInfo.getId()).eq(AccountPlanRecordDO::getType,Constant.AccountPlanRecord_TYPE.销售.getValue()));

            if(ap!=null){
                //accountPlanRecordService.updateAccountPlanRecord(ap,planInfo.getSaleAllCount().negate());
                //删除原金额
                CustomerAccountDO salecustomer=new CustomerAccountDO();
                salecustomer.setCustomerId(ap.getCustomerId());
                salecustomer.setNowCount(ap.getMoneyCount().negate());
                salecustomer.setSaleCount(ap.getMoneyCount().abs().negate());
                salecustomer.setBuyCount(new BigDecimal("0"));
                concurrentHashMap.put(UUID.randomUUID().toString().replace("-", ""),salecustomer);




                //添加金额
                CustomerAccountDO nsalecustomer=new CustomerAccountDO();
                nsalecustomer.setCustomerId(ap.getCustomerId());
                nsalecustomer.setNowCount(planInfo.getSaleAllCount().negate());
                nsalecustomer.setSaleCount(planInfo.getSaleAllCount().abs());
                nsalecustomer.setBuyCount(new BigDecimal("0"));
                concurrentHashMap.put(UUID.randomUUID().toString().replace("-", ""),nsalecustomer);

                ap.setMoneyCount(planInfo.getSaleAllCount().abs().negate());
                accountPlanRecordMapper.updateById(ap);


            }else{
                throw new RuntimeException("数据缺失，不可修改");
            }

            AccountPlanRecordDO cg=accountPlanRecordMapper.selectOne(new LambdaQueryWrapper<AccountPlanRecordDO>().eq(AccountPlanRecordDO::getCustomerId,planInfo.getBuyCustomerId())
                    .eq(AccountPlanRecordDO::getTypeId,planInfo.getId()).eq(AccountPlanRecordDO::getType,Constant.AccountPlanRecord_TYPE.采购.getValue()));
            if(cg!=null){
                //accountPlanRecordService.updateAccountPlanRecord(cg,planInfo.getBuyAllCount());

                CustomerAccountDO buycustomer=new CustomerAccountDO();
                buycustomer.setCustomerId(cg.getCustomerId());
                buycustomer.setNowCount(cg.getMoneyCount().negate());
                buycustomer.setSaleCount(new BigDecimal("0"));
                buycustomer.setBuyCount(cg.getMoneyCount().negate());

                concurrentHashMap.put(UUID.randomUUID().toString().replace("-", ""),buycustomer);



                CustomerAccountDO nbuycustomer=new CustomerAccountDO();
                nbuycustomer.setCustomerId(cg.getCustomerId());
                nbuycustomer.setNowCount(planInfo.getBuyAllCount().abs());
                nbuycustomer.setSaleCount(new BigDecimal("0"));
                nbuycustomer.setBuyCount(planInfo.getBuyAllCount().abs());

                concurrentHashMap.put(UUID.randomUUID().toString().replace("-", ""),nbuycustomer);

                cg.setMoneyCount(planInfo.getBuyAllCount().abs());
                accountPlanRecordMapper.updateById(cg);

            }else{
                throw new RuntimeException("数据缺失，不可修改");
            }

        }else{
            //添加销售公司记录 1销售2采购3付款4收款
            AccountPlanRecordDO ap=new AccountPlanRecordDO();
            ap.setCustomerId(planInfo.getSaleCustomerId());
            ap.setMoneyCount(planInfo.getSaleAllCount().negate());
            ap.setType(Constant.AccountPlanRecord_TYPE.销售.getValue());
            ap.setTypeId(planInfo.getId());
            ap.setPayDate(planInfo.getNowTime());

            accountPlanRecordService.createAccountPlanRecord(ap);

            CustomerAccountDO salecustomer=new CustomerAccountDO();
            salecustomer.setCustomerId(ap.getCustomerId());
            salecustomer.setNowCount(ap.getMoneyCount());
            salecustomer.setSaleCount(ap.getMoneyCount().abs());
            salecustomer.setBuyCount(new BigDecimal("0"));
            concurrentHashMap.put(UUID.randomUUID().toString().replace("-", ""),salecustomer);



            //添加采购公司记录
            AccountPlanRecordDO cg=new AccountPlanRecordDO();
            cg.setCustomerId(planInfo.getBuyCustomerId());
            cg.setMoneyCount(planInfo.getBuyAllCount().abs());
            cg.setType(Constant.AccountPlanRecord_TYPE.采购.getValue());
            cg.setTypeId(planInfo.getId());
            cg.setPayDate(planInfo.getNowTime());
            accountPlanRecordService.createAccountPlanRecord(cg);




            CustomerAccountDO buycustomer=new CustomerAccountDO();
            buycustomer.setCustomerId(cg.getCustomerId());
            buycustomer.setNowCount(cg.getMoneyCount());
            buycustomer.setSaleCount(new BigDecimal("0"));
            buycustomer.setBuyCount(cg.getMoneyCount());


            concurrentHashMap.put(UUID.randomUUID().toString().replace("-", ""),buycustomer);
        }





        //处理月度计划累加
        if(planInfo.getCompanyId()!=null&&planInfo.getCompanyId()>0){
            if(xg){
                MonthPlanInfoDO monthPlanInfoDO=new MonthPlanInfoDO();
                monthPlanInfoDO.setLineCost(old.getLineCost().negate());
                monthPlanInfoDO.setId(old.getCompanyId());
                monthPlanInfoDO.setCapacityUsed(old.getSaleRealCount().negate());
                monthPlanInfoDO.setUsedDownCount(old.getSaleRealCount().negate());
                monthPlanInfoDO.setUsedUpCount(old.getBuyRealCount().negate());
                //上载-下载
                BigDecimal imba=old.getBuyRealCount().subtract(old.getSaleRealCount());
                monthPlanInfoDO.setImbalanceTotal(imba.negate());
                monthPlanInfoDO.setSaleOtherTotal(old.getSaleOtherCount().negate());
                monthPlanInfoDO.setSaleAllCost(old.getSaleAllCount().negate());

                monthPlanInfoDO.setBuyOtherTotal(old.getBuyOtherCount().negate());
                monthPlanInfoDO.setBuyAllCost(old.getBuyAllCount().negate());

                monthMap.put(UUID.randomUUID().toString().replace("-", ""),monthPlanInfoDO);
            }

            MonthPlanInfoDO monthPlanInfoDO=new MonthPlanInfoDO();
            monthPlanInfoDO.setLineCost(planInfo.getLineCost());
            monthPlanInfoDO.setId(planInfo.getCompanyId());
            monthPlanInfoDO.setCapacityUsed(planInfo.getSaleRealCount());
            monthPlanInfoDO.setUsedDownCount(planInfo.getSaleRealCount());
            monthPlanInfoDO.setUsedUpCount(planInfo.getBuyRealCount());
            //上载-下载
            BigDecimal imba=planInfo.getBuyRealCount().subtract(planInfo.getSaleRealCount());
            monthPlanInfoDO.setImbalanceTotal(imba);
            monthPlanInfoDO.setSaleOtherTotal(saleJjf);
            monthPlanInfoDO.setSaleAllCost(planInfo.getSaleAllCount());

            monthPlanInfoDO.setBuyOtherTotal(buyjjf);
            monthPlanInfoDO.setBuyAllCost(planInfo.getBuyAllCount());

            monthMap.put(UUID.randomUUID().toString().replace("-", ""),monthPlanInfoDO);
        }

        //处理合同
        if(old.getSaleContractId()!=null){
            if(xg){
                ContractInfoDO contractInfoDO=new ContractInfoDO();
                contractInfoDO.setId(old.getSaleContractId());
                contractInfoDO.setUsedCount(old.getSaleRealCount().negate());
                contractMap.put(UUID.randomUUID().toString().replace("-", ""),contractInfoDO);
            }
        }
        if(planInfo.getSaleContractId()!=null){


            ContractInfoDO contractInfoDO=new ContractInfoDO();
            contractInfoDO.setId(planInfo.getSaleContractId());
            contractInfoDO.setUsedCount(planInfo.getSaleRealCount());
            contractMap.put(UUID.randomUUID().toString().replace("-", ""),contractInfoDO);
        }

        if(old.getBuyContractId()!=null){
            if(xg){
                ContractInfoDO contractInfoDO=new ContractInfoDO();
                contractInfoDO.setId(old.getBuyContractId());
                contractInfoDO.setUsedCount(old.getBuyRealCount().negate());
                contractMap.put(UUID.randomUUID().toString().replace("-", ""),contractInfoDO);
            }
        }
        if(planInfo.getBuyContractId()!=null){

            ContractInfoDO contractInfoDO=new ContractInfoDO();
            contractInfoDO.setId(planInfo.getBuyContractId());
            contractInfoDO.setUsedCount(planInfo.getBuyRealCount());
            contractMap.put(UUID.randomUUID().toString().replace("-", ""),contractInfoDO);
        }

        planInfoMapper.updateById(planInfo);

        // 返回
        return planInfo.getId();
    }


    @Override
    @Transactional
    public void updatePlanInfo(PlanInfoSaveReqVO createReqVO) {
        // 校验存在
        validatePlanInfoExists(createReqVO.getId());



// 更新
        PlanInfoDO planInfo = BeanUtils.toBean(createReqVO, PlanInfoDO.class);


        //计算
        BigDecimal salePrice=createReqVO.getSalePrice();
        BigDecimal saleCount=createReqVO.getSaleRealCount()==null?new BigDecimal("0"):createReqVO.getSaleRealCount();

        BigDecimal saleOtherPrice=createReqVO.getSaleOtherPrice()==null?new BigDecimal("0"):createReqVO.getSaleOtherPrice();

        //居间总额=居间费*下载量
        BigDecimal saleJjf=saleCount.multiply(saleOtherPrice)/*.multiply(new BigDecimal("10000"))*/;
        planInfo.setSaleOtherCount(saleJjf);
        //真实价格=居间费+销售单价
        BigDecimal saleRealPrice=salePrice.add(saleOtherPrice);
        planInfo.setSaleRealPrice(saleRealPrice);
        //销售额=销售价格*下载量
        planInfo.setSaleAllCount(salePrice.multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/);

        //管输总额=管输单价*下载量
        BigDecimal gsze=planInfo.getLinePrice().multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/;
        planInfo.setLineCost(gsze);


        //采购
        BigDecimal bugPrice=createReqVO.getBuyPrice();
        BigDecimal bugCount=createReqVO.getBuyRealCount()==null?new BigDecimal("0"):createReqVO.getBuyRealCount();
        //采购居间费
        BigDecimal bugOtherPrice=createReqVO.getBuyOtherPrice()==null?new BigDecimal("0"):createReqVO.getBuyOtherPrice();
        //采购居间费
        BigDecimal buyjjf=bugCount.multiply(bugOtherPrice)/*.multiply(new BigDecimal("10000"))*/;
        planInfo.setBuyOtherCount(buyjjf);
        //购买额
        BigDecimal buyRealPrice=bugPrice.add(bugOtherPrice);
        planInfo.setBuyRealPrice(buyRealPrice);

        planInfo.setBuyAllCount(bugPrice.multiply(bugCount)/*.multiply(new BigDecimal("10000"))*/);
        //毛差

        BigDecimal mc=salePrice.subtract(planInfo.getLinePrice()).subtract(bugPrice).subtract(saleOtherPrice).subtract(bugOtherPrice);

        // BigDecimal mc=salePrice.subtract(bugPrice).subtract(planInfo.getSaleOtherPrice()).subtract(planInfo.getBuyOtherPrice());
        planInfo.setGainCount(mc);
        //总利润=毛差*下载量
        //planInfo.setProfit(planInfo.getSaleAllCount().subtract(planInfo.getBuyAllCount()).subtract(planInfo.getSaleOtherCount()).subtract(planInfo.getBuyOtherCount()));
        planInfo.setProfit(mc.multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/);

        //计算
//        BigDecimal salePrice=createReqVO.getSalePrice();
//        Integer type=createReqVO.getCheckType();//1 自己托运
//        if(type==1){//暂定 自己托运管输费算销售成本
//            salePrice=salePrice.add(createReqVO.getLinePrice());
//        }
//        BigDecimal saleCount=createReqVO.getSaleRealCount();
//        BigDecimal saleOtherPrice=createReqVO.getSaleOtherPrice()==null?new BigDecimal("0"):createReqVO.getSaleOtherPrice();
//
//        //销售居间费
//        BigDecimal jjf=saleCount.multiply(saleOtherPrice)/*.multiply(new BigDecimal("10000"))*/;
//        planInfo.setSaleOtherCount(jjf);
//        //销售额
//        planInfo.setSaleRealPrice(salePrice);
//        planInfo.setSaleAllCount(salePrice.multiply(saleCount)/*.multiply(new BigDecimal("10000"))*/);
//
//        //采购
//        BigDecimal bugPrice=createReqVO.getBuyPrice();
//
//        BigDecimal bugCount=createReqVO.getBuyRealCount();
//
//        BigDecimal bugOtherPrice=createReqVO.getBuyOtherPrice()==null?new BigDecimal("0"):createReqVO.getBuyOtherPrice();
//        //采购居间费
//        BigDecimal buyjjf=bugCount.multiply(bugOtherPrice)/*.multiply(new BigDecimal("10000"))*/;
//        planInfo.setBuyOtherCount(buyjjf);
//        //购买额
//        planInfo.setBuyRealPrice(bugPrice);
//        planInfo.setBuyAllCount(bugPrice.multiply(bugCount)/*.multiply(new BigDecimal("10000"))*/);
//        //毛差
//
//
//
//        BigDecimal mc=salePrice.subtract(planInfo.getLinePrice()).subtract(bugPrice).subtract(planInfo.getSaleOtherPrice()).subtract(planInfo.getBuyOtherPrice());
//       // BigDecimal mc=salePrice.subtract(bugPrice).subtract(planInfo.getSaleOtherPrice()).subtract(planInfo.getBuyOtherPrice());
//
//        planInfo.setGainCount(mc);
//        //总利润 量不同没意义
//        planInfo.setProfit(planInfo.getSaleAllCount().subtract(planInfo.getBuyAllCount()).subtract(planInfo.getSaleOtherCount()).subtract(planInfo.getBuyOtherCount()));
        //
        planInfo.setSaleBillStatus(0);
        planInfo.setSaleAccountStatus(0);
        planInfo.setBuyBillStatus(0);
        planInfo.setBuyAccountStatus(0);


        planInfoMapper.updateById(planInfo);

        //修改销售公司记录 1销售2采购3付款4收款
       /* */
       /* AccountPlanRecordDO ap=accountPlanRecordMapper.selectOne(new LambdaQueryWrapper<AccountPlanRecordDO>().eq(AccountPlanRecordDO::getCustomerId,planInfo.getSaleCustomerId())
                .eq(AccountPlanRecordDO::getTypeId,planInfo.getId()).eq(AccountPlanRecordDO::getType,Constant.AccountPlanRecord_TYPE.销售.getValue()));
        if(ap!=null){
            accountPlanRecordService.updateAccountPlanRecord(ap,planInfo.getSaleAllCount().negate());
        }else{
            throw new RuntimeException("数据缺失，不可修改");
        }

        AccountPlanRecordDO cg=accountPlanRecordMapper.selectOne(new LambdaQueryWrapper<AccountPlanRecordDO>().eq(AccountPlanRecordDO::getCustomerId,planInfo.getBuyCustomerId())
                .eq(AccountPlanRecordDO::getTypeId,planInfo.getId()).eq(AccountPlanRecordDO::getType,Constant.AccountPlanRecord_TYPE.采购.getValue()));
        if(cg!=null){
            accountPlanRecordService.updateAccountPlanRecord(cg,planInfo.getBuyAllCount());
        }else{
            throw new RuntimeException("数据缺失，不可修改");
        }*/



       /* AccountPlanRecordDO ap=new AccountPlanRecordDO();
        ap.setCustomerId(planInfo.getSaleCustomerId());
        ap.setMoneyCount(planInfo.getSaleAllCount().negate());
        ap.setType(Constant.AccountPlanRecord_TYPE.销售.getValue());
        ap.setTypeId(planInfo.getId());
        accountPlanRecordService.createAccountPlanRecord(ap);
        //添加采购公司记录
        AccountPlanRecordDO cg=new AccountPlanRecordDO();
        cg.setCustomerId(planInfo.getBuyCustomerId());
        cg.setMoneyCount(planInfo.getBuyAllCount());
        cg.setType(Constant.AccountPlanRecord_TYPE.采购.getValue());
        cg.setTypeId(planInfo.getId());
        accountPlanRecordService.createAccountPlanRecord(cg);*/


    }

    @Override
    @Transactional
    public void deletePlanInfo(Long id) {
        // 校验存在
        validatePlanInfoExists(id);
       PlanInfoDO planInfo= planInfoMapper.selectById(id);
        // 删除
        if(planInfo.getBuyAccountStatus()!=0||planInfo.getSaleAccountStatus()!=0||planInfo.getBuyBillStatus()!=0||planInfo.getSaleBillStatus()!=0){
            throw exception(DISABLE_DELETE);
        }

        boolean xg=false;
        if(planInfo.getStatus()==1){
           xg=true;
        }

        if(xg){
            //同时删除记录
            AccountPlanRecordDO ap=accountPlanRecordMapper.selectOne(new LambdaQueryWrapper<AccountPlanRecordDO>().eq(AccountPlanRecordDO::getCustomerId,planInfo.getSaleCustomerId())
                    .eq(AccountPlanRecordDO::getTypeId,planInfo.getId()).eq(AccountPlanRecordDO::getType,Constant.AccountPlanRecord_TYPE.销售.getValue()));
            if(ap!=null){
                if(xg){
                    CustomerAccountDO salecustomer=new CustomerAccountDO();
                    salecustomer.setCustomerId(ap.getCustomerId());
                    salecustomer.setNowCount(ap.getMoneyCount().negate());
                    salecustomer.setSaleCount(ap.getMoneyCount().abs().negate());
                    salecustomer.setBuyCount(new BigDecimal("0"));
                    concurrentHashMap.put(UUID.randomUUID().toString().replace("-", ""),salecustomer);
                }



                accountPlanRecordService.deleteAccountPlanRecord(ap);
            }else{
                throw new RuntimeException("数据缺失，不可修改");
            }

            AccountPlanRecordDO cg=accountPlanRecordMapper.selectOne(new LambdaQueryWrapper<AccountPlanRecordDO>().eq(AccountPlanRecordDO::getCustomerId,planInfo.getBuyCustomerId())
                    .eq(AccountPlanRecordDO::getTypeId,planInfo.getId()).eq(AccountPlanRecordDO::getType,Constant.AccountPlanRecord_TYPE.采购.getValue()));
            if(cg!=null){
                if(xg) {
                    CustomerAccountDO buycustomer = new CustomerAccountDO();
                    buycustomer.setCustomerId(cg.getCustomerId());
                    buycustomer.setNowCount(cg.getMoneyCount().negate());
                    buycustomer.setSaleCount(new BigDecimal("0"));
                    buycustomer.setBuyCount(cg.getMoneyCount().negate());

                    concurrentHashMap.put(UUID.randomUUID().toString().replace("-", ""), buycustomer);

                }
                accountPlanRecordService.deleteAccountPlanRecord(cg);
            }else{
                throw new RuntimeException("数据缺失，不可修改");
            }


            if(xg &&planInfo.getCompanyId()!=null&&planInfo.getCompanyId()>0){
                MonthPlanInfoDO monthPlanInfoDO=new MonthPlanInfoDO();
                monthPlanInfoDO.setLineCost(planInfo.getLineCost().negate());
                monthPlanInfoDO.setId(planInfo.getCompanyId());
                monthPlanInfoDO.setCapacityUsed(planInfo.getSaleRealCount().negate());
                monthPlanInfoDO.setUsedDownCount(planInfo.getSaleRealCount().negate());
                monthPlanInfoDO.setUsedUpCount(planInfo.getBuyRealCount().negate());
                //上载-下载
                BigDecimal imba=planInfo.getBuyRealCount().subtract(planInfo.getSaleRealCount());
                monthPlanInfoDO.setImbalanceTotal(imba.negate());
                monthPlanInfoDO.setSaleOtherTotal(planInfo.getSaleOtherCount().negate());
                monthPlanInfoDO.setSaleAllCost(planInfo.getSaleAllCount().negate());

                monthPlanInfoDO.setBuyOtherTotal(planInfo.getBuyOtherCount().negate());
                monthPlanInfoDO.setBuyAllCost(planInfo.getBuyAllCount().negate());

                monthMap.put(UUID.randomUUID().toString().replace("-", ""),monthPlanInfoDO);
            }


            if(xg&&planInfo.getSaleContractId()!=null){
                ContractInfoDO contractInfoDO=new ContractInfoDO();
                contractInfoDO.setId(planInfo.getSaleContractId());
                contractInfoDO.setUsedCount(planInfo.getSaleRealCount().negate());
                contractMap.put(UUID.randomUUID().toString().replace("-", ""),contractInfoDO);
            }

            if(xg&&planInfo.getBuyContractId()!=null){
                ContractInfoDO contractInfoDO=new ContractInfoDO();
                contractInfoDO.setId(planInfo.getBuyContractId());
                contractInfoDO.setUsedCount(planInfo.getBuyRealCount().negate());
                contractMap.put(UUID.randomUUID().toString().replace("-", ""),contractInfoDO);
            }

        }

        planInfoMapper.deleteById(id);

    }

    private void validatePlanInfoExists(Long id) {
        if (planInfoMapper.selectById(id) == null) {
            throw exception(PLAN_INFO_NOT_EXISTS);
        }
    }

    @Override
    public PlanInfoDO getPlanInfo(Long id) {
        return planInfoMapper.selectById(id);
    }

    @Override
    public PageResult<PlanInfoDO> getPlanInfoPage(PlanInfoPageReqVO pageReqVO) {
        return planInfoMapper.selectPage(pageReqVO);
    }

}